//
//  AuthManage.swift
//  鉴权管理
//
//  Created by chen on 2025/5/2.
//
import SwiftUI
import ATAuthSDK
import UIKit
import ToastUI

@MainActor
class AuthManager: ObservableObject {
    
    static let shared = AuthManager()
    
    @Published var isLogin: Bool = false
    
    @Published var oneKeyLoginSupport: Bool = false
    
    @Published var phone: String = ""

    init() {
        // 检查登录状态
        if UserDefaults.standard.bool(forKey: "isLogin") {
            self.isLogin = true
        }
        
        if let phone = UserDefaults.standard.string(forKey: "phone") {
            self.phone = phone
        }
    }

    func login(phone: String, token: String) {
        UserDefaults.standard.set(phone, forKey: "phone")
        UserDefaults.standard.set(token, forKey: "token")
        UserDefaults.standard.set(true, forKey: "isLogin")
        self.isLogin = true
        self.phone = phone
    }

    func logout() {
        UserDefaults.standard.set(false, forKey: "isLogin")
        UserDefaults.standard.removeObject(forKey: "phone")
        UserDefaults.standard.removeObject(forKey: "token")
        self.isLogin = false
        self.phone = ""
    }
    
    func getToken() -> String? {
        return UserDefaults.standard.string(forKey: "token")
    }
    
    func toLogin() {
        if oneKeyLoginSupport {
            toOneKeyLoginPage()
        } else {
            Router.shared.to(.loginView)
        }
    }
    
    func toOneKeyLoginPage() {
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
           let viewController = windowScene.windows.first?.rootViewController {
            
            let instance = ATAuthSDK.TXCommonHandler.sharedInstance()
            
            instance.getLoginToken(withTimeout: TimeInterval(3), controller: viewController, model: createLoginModel()) { (data: [AnyHashable : Any]) in
                
                let resultCode = data["resultCode"] as! String
                
                switch resultCode {
                case "600002":
                    Router.shared.to(.loginView)
                case "700001":
                    instance.cancelLoginVC(animated: true) {
                        Router.shared.to(.loginView)
                    }
                case "700002":
                    let isChecked = data["isChecked"] as! Int
                    if isChecked == 0 {
                        ToastAsync("请先阅读并同意协议");
                    }
                case "700000":
                    // 返回之前的页面
                    Router.shared.back()
                case "600000":
                    // 600000-成功获取Token
                    let token = data["token"] as! String
                    self.doLogin(token: token)
                case "600011", "600015", "600013", "600014":
                    // 600011-获取Token失败
                    ToastAsync("登录服务异常");
                default:
                    Logger.shared.info("getLoginToken:\(data)")
                }
            }
        }
    }
    
    func createLoginModel() -> TXCustomModel {
        let model = TXCustomModel()
        model.supportedInterfaceOrientations = .portrait
        model.navColor = UIColor.white
        model.navTitle = NSAttributedString(string: "登录")
        model.hideNavBackItem = false
        model.logoImage = UIImage.init(named: "logo")!
        
        model.checkBoxIsChecked = true
        model.autoHideLoginLoading = false
        
        return model
    }
    
    private func doLogin(token: String) {
        Task{
            
            let param = OneKeyLoginReq(token: token)
            
            await NetManager.server.httpPost(.oneKeyLogin, bodyParam: param) { (data: OneKeyLoginResp) in
                self.login(phone: data.phone, token: data.token)
                self.phone = data.phone
                
                ATAuthSDK.TXCommonHandler.sharedInstance().cancelLoginVC(animated: true) {
                    Router.shared.back()
                }
            }
            ATAuthSDK.TXCommonHandler.sharedInstance().hideLoginLoading()
        }
    }
}

